package de.nabble.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;

import de.nabble.Nabble;

/**
 * All letters.
 * @author Tom
 *
 */
public class LetterBag {
	private ResourceBundle bundle;
	private int letterCount;
	
	private List<Letter> bag;
	private Letter[] backup;
	
	public LetterBag() {
		bag = new ArrayList<Letter>();
		bundle = ResourceBundle.getBundle(Nabble.LETTER_BUNDLE_PATH);
		loadAllLetters();
		Collections.shuffle(bag);
		
		backup = new Letter[bag.size()];
		backup = bag.toArray(backup);
		
		letterCount = bag.size();
	}
	
	public Letter takeLetter() {
		if(letterCount != 0) {
			letterCount--;
			return bag.remove(bag.size() - 1);
		}
		
		throw new NoMoreLettersException("No more letters in bag!");
	}
	
	/**
	 * Loads all letters.
	 */
	private void loadAllLetters() {	
		for(String s : bundle.keySet()) {
			Letter letter = loadLetter(s);
			for(int i = 0; i < letter.getCount(); i++) {
				bag.add(letter.clone());
			}
		}
	}
	
	/**
	 * Loads a letter from the resource bundle specified by BUNDLE_PATH
	 * @param letterKey a key must look like "Letter.A"
	 * @return the letter object constructed by the key.
	 */
	private Letter loadLetter(String letterKey) {
		String[] all = bundle.getString(letterKey).split(",");
		char value = all[0].charAt(0);
		int points = Integer.valueOf(all[1]);
		int count = Integer.valueOf(all[2]);
		
		return new Letter(points, value, count);
	}
	
	/**
	 * Reine Hilfsmethode. Nicht im Spielablauf benutzen, da 
	 * sie die steine nicht entfernt!!
	 * 
	 * @param c
	 * @return
	 */
	public Letter getSpecificLetter(char c) {
		c = Character.toUpperCase(c);
		for(Letter l : backup) {
			if(l.getValue() == c) {
				return l;
			}
		}
		
		return null;
	}
	
	public int getLetterCount() {
		return letterCount;
	}
	
	@Override
	public String toString() {
		return bag.toString();
	}
	
	public static class NoMoreLettersException extends RuntimeException {
		
		public NoMoreLettersException(String msg) {
			super(msg);
		}
		
		private static final long serialVersionUID = -2461736977822296322L;
		
	}
}
